package priv.liaohaolong.fullstacktest.filter;

import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import priv.liaohaolong.fullstacktest.util.JwtUtils;

import java.io.IOException;

@Slf4j
@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;

    private final JwtUtils jwtUtils;

    @Autowired
    public JwtRequestFilter(UserDetailsService userDetailsService, JwtUtils jwtUtils) {
        this.userDetailsService = userDetailsService;
        this.jwtUtils = jwtUtils;
    }

    /**
     * 若请求头中包含 JWT，则提取 JWT 并验证。<br>
     * 若 JWT 有效则创建认证信息并设置到 SecurityContextHolder 中，继续执行过滤器链；<br>
     * 若 JWT 无效则继续执行过滤器链，不设置认证信息，后续的 UsernamePasswordAuthenticationFilter 会因为认证信息为空，且
     *
     * @param request request
     * @param response response
     * @param filterChain filterChain
     * @throws ServletException ServletException
     * @throws IOException IOException
     */
    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        log.info("JWT Request Filter: {} {}", request.getMethod(), request.getRequestURI());

        // 获取请求头
        String authorizationHeader = request.getHeader("Authorization");
        // 判断请求头是否有效
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            // 提取 JWT
            String jwt = authorizationHeader.substring(7);
            // 提取 Username
            String username;
            try {
                username = jwtUtils.extractUsername(jwt);
            } catch (JwtException | IllegalArgumentException e) {
                log.info("JWT Request Filter: JWT is invalid");

                // JWT 无效，继续执行过滤器链
                filterChain.doFilter(request, response);
                return;
            }
            // 查询认证信息
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            // 验证 JWT
            if (jwtUtils.validateToken(jwt, userDetails)) {
                log.info("JWT Request Filter: JWT is valid");

                // 创建认证信息
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                // 设置请求信息，以便后续的其他 Filter 或 Controller 使用
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 设置认证信息
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }

        // 继续执行过滤器链
        filterChain.doFilter(request, response);
    }

}
